package com.zhao.newcoder.service;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.zhao.newcoder.VO.LoginResult;
import com.zhao.newcoder.Repository.AuthUserRepository;

// import com.zhao.newcoder.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.druid.util.Utils;
import com.zhao.newcoder.DTO.AuthUser;

@Service
public class LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginService.class);
    public static final Long tokenExpire = 1000000000L;

    @Autowired
    AuthUserRepository authUserRepository;

    public LoginResult register(String username, String password, Integer accountType) {
        // 创建实体
        AuthUser authUser = new AuthUser();
        // 判断注册用户名在表中是否存在
        boolean exist = existUsername(username, accountType);
        LoginResult loginResult = new LoginResult();
        if (exist) {
            System.out.println("This user exists! " + username);
            logger.info("This user exists! username={}", username);
            loginResult.setUserId(0L);
            loginResult.setToken("");
            loginResult.setUsername(username);
            loginResult.setCodeDesc("您输入的账号已经被注册了");
            return loginResult;
        } else {
            // 加密
            String encodedPassword = Utils.md5(password).toLowerCase();
            authUser.setPassword(encodedPassword);
            authUser.setMobile(username);
            authUser.setStatus(accountType);
            authUserRepository.save(authUser);
            loginResult.setCode("200");
            loginResult.setCodeDesc("注册成功");
            // loginResult.setUserId(0L);
            return loginResult;
        }

    }

    private boolean existUsername(String username, Integer accountType) {
        List authList = authUserRepository.findByMobile(username);
        if (authList.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    public AuthUser login(String username, String password) {
        String encodedPassword = Utils.md5(password).toLowerCase();
        AuthUser loginess = authUserRepository.findByMobileAndPassword(username, encodedPassword);
        return loginess;
    }

}
